import {
  Table, Input, InputNumber, Popconfirm, Form, Divider, message,
} from 'antd';
import * as React from "react";
import GiftGoodsService from "../../business/gift/GiftGoodsService";
import styles from './GoodsList.css';

const FormItem = Form.Item;
// @ts-ignore
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  getInput = () => {
    // @ts-ignore
    if (this.props.inputType === 'number') {
      return <InputNumber />;
    }
    return <Input />;
  };

  render() {
    // @ts-ignore
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      ...restProps
    } = this.props;
    return (
      <EditableContext.Consumer>
        {(form) => {
          const { getFieldDecorator } = form;
          return (
            <td {...restProps}>
              {editing ? (
                <FormItem style={{ margin: 0 }}>
                  {getFieldDecorator(dataIndex, {
                    rules: [{
                      required: true,
                      message: `请输入 ${title}!`,
                    }],
                    initialValue: record[dataIndex],
                  })(this.getInput())}
                </FormItem>
              ) : restProps.children}
            </td>
          );
        }}
      </EditableContext.Consumer>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.giftGoodsService =new GiftGoodsService();
    this.callBackQueryList = this.callBackQueryList.bind(this);

  }
  state = {
    editingKey: '',
    giftData:[],
  };
  columns= [{
    title: '礼品名称',
    dataIndex: 'goodsName',
    key: 'goodsName',
    render: text => <a href="javascript:;">{text}</a>,
    editable: true,
  }, {
    title: '礼品编号',
    dataIndex: 'goodsSn',
    key: 'goodsSn',
    width:'20%',
    editable: false,
  }, {
    title: '积分',
    dataIndex: 'goodsPoints',
    key: 'goodsPoints',
    editable: true,
  }, {
    title: '库存',
    dataIndex: 'goodsQuantity',
    key: 'goodsQuantity',
    editable: true,
  }, {
    title: '浏览',
    dataIndex: 'clickCount',
    key: 'clickCount',
    editable: false,
  }, {
    title: '兑出',
    dataIndex: 'exchangeCount',
    key: 'exchangeCount',
    editable: false,
  }, {
    title: '操作',
    key: 'action',
    render: (text, record) => {
      const editable = this.isEditing(record);
      return (
        <div>
          {editable ? (
            <span>
                  <EditableContext.Consumer>
                    {form => (
                      <a
                        href="javascript:;"
                        onClick={() => this.save(form, record.goodsSn)}
                        style={{ marginRight: 8 }}
                      >
                        保存
                      </a>
                    )}
                  </EditableContext.Consumer>
                  <Popconfirm
                    title="确定要取消吗?"
                    okText="确定"
                    cancelText="关闭"
                    onConfirm={() => this.cancel()}
                  >
                    <a>取消</a>
                  </Popconfirm>
                </span>
          ) : (
            <a onClick={() => this.edit(record.goodsSn)}>修改</a>
          )}
        </div>
      );
    },
  }];

  isEditing = record => record.goodsSn === this.state.editingKey;

  cancel = () => {
    this.setState({ editingKey: '' });
  };

  save(form, key) {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      row.goodsSn = key;
      let token = sessionStorage.getItem('adminLoginToken');
      this.giftGoodsService.updateGiftGoods(token,row,this.updateGoodsCallback);
      this.setState({
        editingKey:'',
      });
      this.componentDidMount();
    });
  }

  updateGoodsCallback(res,isSuccess){
    if(!isSuccess|| res.code!='200'){
      message.info(res.message);
      return;
    }


  }

  edit(key) {
    this.setState({ editingKey: key });
  }

  giftGoodsService:GiftGoodsService;
  callBackQueryList(giftList,isSuccess){
    if(!isSuccess || giftList.code !="000000"){
      message.info(giftList.message);
    }else{
      this.setState({giftData: giftList.data.dataList});
    }
  }

  componentDidMount(){
    console.info("giftPage htpp start");
    let data ={
      username:sessionStorage.getItem('username')
    };
    this.giftGoodsService.queryList(this.callBackQueryList);
  }

  render() {
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };

    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'goodsName' ? 'text' : 'number',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      <div className={styles.normal}>
      <Table
        components={components}
        bordered
        dataSource={this.state.giftData}
        columns={columns}
        rowKey={record=>record.goodsSn}
      />
      </div>
    );
  }
}
export default EditableTable;
